package sysmgr.service.impl;

import commmon.md5.MD5;
import sysmgr.bean.Role;
import sysmgr.bean.Staff;
import sysmgr.dao.StaffDao;
import sysmgr.dao.impl.StaffDaoImpl;
import sysmgr.service.StaffService;
import java.util.List;

public class StaffServicempl implements StaffService {
    public static final int pwdTimes=1000;
    public static int number=0;
    @Override
    public int updateStaff(Staff staff) {
        return 0;
    }


    @Override
    public int deleteStaff(Staff staff) {
        return 0;
    }

    @Override
    public List<Staff> queryStaff(Staff staff) {
        return null;
    }

    @Override
    public synchronized String staffLogin(Staff staff) {
        number=0;
        StaffDao dao=new StaffDaoImpl();
        Staff temp=dao.staffLogin(staff);
        if(temp!=null){
           String strPwd=this.getPwdAccordingBySalt(staff.getPwd(),temp.getSalt());
           if(strPwd.equals(temp.getPwd())){
               List<Role> roles = dao.queryRole(temp.getId());
               // 查询出角色信息
               return queryRole(roles);
           }
        }
        return null;
    }

    //对密码进行加盐并且通过对应的迭代次数来产生新的密码
    public String getPwdAccordingBySalt(String pwd,String salt) {
        String md5Str = pwd + salt;
        String str=MD5.getMD5ofStr(md5Str);
        while (number < pwdTimes){
            number++;
            //System.out.println("========"+number+"========"+str);
            return getPwdAccordingBySalt(str,salt);
        }

        return str;
    }

    private String queryRole(List<Role> roles){
        for (Role role : roles) {
            if(role.getRoleName().equals("Admin")) {
                // 如果admin  就跳转到后台 aaa.jsp
                return "Home.jsp";
            }else if(role.getRoleName().equals("user")){
                // 如果是user 就跳转到前台 main.jsp
                return "main.jsp";
            }
        }
        return "";
    }


    public static void main(String[] args) {
        StaffServicempl st=new sysmgr.service.impl.StaffServicempl();
       System.out.println(st.getPwdAccordingBySalt("3333","3333"));
    }
}
